package com.gwaeron.game;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

import com.golden.gamedev.engine.BaseIO;
import com.golden.gamedev.object.GameFont;
import com.golden.gamedev.util.FileUtil;

public class StringHandler {

	private static StatTracker stats = StatTracker.get();

	public static int nthOccurrence(String str, char c, int n) {
		int pos = str.indexOf(c, 0);
		while (n-- > 0 && pos != -1)
			pos = str.indexOf(c, pos + 1);
		return pos;
	}

	public static String handleString(BaseIO bsIO, String s, GameFont font,
			boolean hasPortrait) {
		String ret = new String(s);
		ret = replacePlaceHolders(bsIO, ret);
		ret = formatTimeInString(ret);
		return ret;
	}


	public static String replacePlaceHolders(BaseIO bsIO, String s) {
		String ret = new String(s);
		ret = ret.replace("%MINUTES_PLAYED", stats.getMinutesPlayed() + "");
		ret = ret.replace("%HOURS_PLAYED", stats.getHoursPlayed() + "");
		ret = ret.replace("%SECONDS_PLAYED", stats.getSecondsPlayed() + "");
		ret = ret.replace("%DAYS_PLAYED", stats.getDaysPlayed() + "");
		while (ret.contains("%")) {
			StringBuilder bob = new StringBuilder("");
			bob.append('%');
			int next = ret.indexOf('%');
			char curr = '\0';
			next++;
			while (Character.isUpperCase(curr = ret.charAt(next))
					|| curr == '_') {
				bob.append(curr);

				if (next >= ret.length() - 1)
					break;
				next++;
			}
			System.out.println("Replacing\n  " + bob.toString() + "\nwith\n  "
					+ getString(bob.toString()));
			ret = ret.replace(bob.toString(), getString(bob.toString()));
		}
		return ret;
	}

	public static String formatTimeInString(String s) {
		String ret = new String(s);
		ret = ret.replace("0 days, ", "");
		if (ret.startsWith("1 days"))
			ret = ret.replace("1 days", "1 day");
		ret = ret.replace(" 1 hours", " 1 hour");
		ret = ret.replace(" 1 minutes", " 1 minute");
		ret = ret.replace(" 1 seconds", " 1 second");
		return ret;
	}

	private static String getString(String placeHolder) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(
					com.gwaeron.game.RPGGame.class.getResource("strings.dat")
							.toURI())));
			String line;
			while ((line = br.readLine()) != null) {
				if (line.substring(0, line.indexOf('=')).equals(placeHolder)) {
					return line.substring(line.indexOf('=') + 1);
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "[STRING ERROR]";
	}
}
